package com.pdstudio.carrecom.ui.activity.owner;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.pdstudio.carrecom.R;
import com.pdstudio.carrecom.api.HttpExecuteJson;
import com.pdstudio.carrecom.api.HttpExecuteJson.httpReturnJson;
import com.pdstudio.carrecom.api.ServiceHelper;
import com.pdstudio.carrecom.app.AppContext;
import com.pdstudio.carrecom.bean.Boutique;
import com.pdstudio.carrecom.bean.ResultInfo;
import com.pdstudio.carrecom.bean.WeatherInfo;
import com.pdstudio.carrecom.bean.WeatherList;
import com.pdstudio.carrecom.bean.owner.Book;
import com.pdstudio.carrecom.logger.Logger;
import com.pdstudio.carrecom.tools.JsonUtil;
import com.pdstudio.carrecom.tools.StringUtils;
import com.pdstudio.carrecom.ui.activity.buy.ActivityBoutiqueDetail;
import com.pdstudio.carrecom.ui.adapter.BoutiqueListAdapter;
import com.pdstudio.carrecom.ui.adapter.owner.BooksListAdapter;
import com.pdstudio.carrecom.ui.adapter.owner.NewsListAdapter;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * 类: ActivityCzbd <br>
 * 描述: 我是车主——车主宝典 <br>
 * 作者: ws <br>
 * 时间: 2015-6-15 下午11:32:03
 */
public class ActivityCzbd extends Activity implements OnClickListener,
		OnRefreshListener2<ListView>, OnItemClickListener {

	private static final String TAG = "ActivityCzbd";

	private static final int MSG_WHAT_ABOUT = 1;

	private TextView txtTitle;
	private ImageView ivBack;
	private PullToRefreshListView mPullRefreshListView;
	private BooksListAdapter mAdapter;
	private List<Book> mBoutiques = new ArrayList<>();

	private ResultInfo mResultInfo;

	private AppContext mAppContext = AppContext.getInstance();

	/** 刷新页码,从1开始 */
	private int mPageIndex = 1;
	/** 刷新数据条数 */
	private int mPageSize = 10;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_boutique);
		initTitle();
		initView();
	}

	@Override
	protected void onResume() {
		super.onResume();

		getBoutiques();
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Logger.i(TAG, msg);
			switch (msg.what) {
			case MSG_WHAT_ABOUT:// 关于
				if (mBoutiques != null) {
					if (mBoutiques.size() > 0) {
						mBoutiques = (List<Book>) msg.obj;
						// mAdapter.notifyDataSetChanged();

						initData();
					} else {
						Toast.makeText(ActivityCzbd.this, "没有更多数据了",
								Toast.LENGTH_SHORT).show();

					}

					mPullRefreshListView.onRefreshComplete();
					isRefreshing = false;
				}
				break;

			default:
				break;
			}
		}
	};

	/**
	 * 方法: initTitle <br>
	 * 描述: 初始化页面标题 <br>
	 * 作者: ws <br>
	 * 时间: 2015-5-24 下午5:46:11
	 */
	private void initTitle() {
		txtTitle = (TextView) findViewById(R.id.title_text_nav);

		txtTitle.setText("车主宝典");

		ivBack = (ImageView) findViewById(R.id.title_back);
		ivBack.setOnClickListener(this);
	}

	private void initView() {
		mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.listview_boutique);
		mPullRefreshListView.setOnRefreshListener(this);
		mPullRefreshListView.setOnItemClickListener(this);
		mPullRefreshListView.setMode(Mode.BOTH);


	}

	private void initData() {
		mAdapter = new BooksListAdapter(this, mBoutiques);
		mPullRefreshListView.setAdapter(mAdapter);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_back:
			finish();
			break;
		}
	}

	/**
	 * 
	 * 方法: getBoutiques <br>
	 * 描述: 获取精品列表 <br>
	 * 作者: ws <br>
	 * 时间: 2015-6-16 上午12:27:40
	 */
	private void getBoutiques() {
		try {
			HttpExecuteJson http = new HttpExecuteJson(this,
					mNewCarBoutiqueListener);
			String url = ServiceHelper.OwnerCzbd;
			Map<String, Object> rps = new HashMap<String, Object>();
			rps.put("os", "android");
			rps.put("size", "30-60");
			rps.put("start", ((mPageIndex - 1) * mPageSize) + 1);
			rps.put("end", mPageIndex * mPageSize);
			rps.put("uid", mAppContext.getUserId());
			Logger.i(url);
			http.get(url, rps);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private httpReturnJson mNewCarBoutiqueListener = new httpReturnJson() {

		@Override
		public void onSuccess(String result) {
			Logger.json(result);
			ResultInfo resultInfo = null;
			try {
				resultInfo = new Gson().fromJson(result,
						new TypeToken<ResultInfo>() {
						}.getType());
				if ((resultInfo != null)
						&& (resultInfo.msg
								.equals(ServiceHelper.msg_code_sucess))) {
					try {
						mResultInfo = resultInfo;
						Logger.i("天气", resultInfo);

						mBoutiques = JsonUtil.fromJsonArray(
								JsonUtil.toJson(mResultInfo.data),
								Book.class);
						Message msg = new Message();
						msg.obj = mBoutiques;
						msg.what = MSG_WHAT_ABOUT;
						mHandler.sendMessage(msg);

					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {

				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		@Override
		public void onFailure(int error, String msg) {

		}

		@Override
		public void onCancel() {

		}
	};

	/** 是否刷新 */
	private boolean isRefreshing = false;

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		if (!isRefreshing) {
			isRefreshing = true;

			mPageIndex = 1;
			String label = DateUtils.formatDateTime(getApplicationContext(),
					System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
							| DateUtils.FORMAT_SHOW_DATE
							| DateUtils.FORMAT_ABBREV_ALL);

			// Update the LastUpdatedLabel
			refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
			refreshView.getLoadingLayoutProxy(false, true).setPullLabel(
					getString(R.string.pull_to_refresh_pull_label));
			refreshView.getLoadingLayoutProxy(false, true)
					.setRefreshingLabel(
							getString(R.string.pull_to_refresh_refreshing_label));
			refreshView.getLoadingLayoutProxy(false, true)
					.setReleaseLabel(
							getString(R.string.pull_to_refresh_release_label));

			getBoutiques();
		} else {
			mPullRefreshListView.onRefreshComplete();
		}

	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
		if (!isRefreshing) {
			isRefreshing = true;

			mPageIndex++;
			String label = DateUtils.formatDateTime(getApplicationContext(),
					System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
							| DateUtils.FORMAT_SHOW_DATE
							| DateUtils.FORMAT_ABBREV_ALL);

			// Update the LastUpdatedLabel
			refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
			refreshView.getLoadingLayoutProxy(false, true).setPullLabel(
					getString(R.string.pull_to_refresh_from_bottom_pull_label));
			refreshView.getLoadingLayoutProxy(false, true)
					.setRefreshingLabel(
							getString(R.string.pull_to_refresh_from_bottom_refreshing_label));
			refreshView.getLoadingLayoutProxy(false, true)
					.setReleaseLabel(
							getString(R.string.pull_to_refresh_from_bottom_release_label));

			getBoutiques();
		} else {
			mPullRefreshListView.onRefreshComplete();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		Intent intent = new Intent(this, ActivityBoutiqueDetail.class);  
		Book boutique = mBoutiques.get(arg2);
		Bundle bundle = new Bundle();
		bundle.putSerializable("BOUTIQUE_DETAIL", boutique);
		intent.putExtras(bundle);
//		startActivity(intent);  
		
	}

}
